package com.wish.blessingroad.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wish.blessingroad.common.Constant;
import com.wish.blessingroad.common.RedisKey;
import com.wish.blessingroad.dao.BlessingMapper;
import com.wish.blessingroad.dao.OrdersMapper;
import com.wish.blessingroad.entity.Blessing;
import com.wish.blessingroad.entity.Orders;
import com.wish.blessingroad.entity.User;
import com.wish.blessingroad.service.IBlessingService;
import com.wish.blessingroad.service.IOrdersService;
import com.wish.blessingroad.util.JedisUtil;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.convert.EntityWriter;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.params.SetParams;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 订单实现类
 * </p>
 *
 * @author dhc
 * @since 2019-02-18
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {
    private static final Logger LOG = LoggerFactory.getLogger(OrdersServiceImpl.class);
    @Resource
    private OrdersMapper ordersMapper;
    @Autowired
    private IBlessingService blessingServiceImpl;
    @Autowired
    private JedisUtil jedisUtil;

    /**
     * 充值回调，变更订单状态
     *
     * @param orderId
     * @param wxOrderId
     * @param status
     * @param openId
     */
    @Transactional
    public void updateOrder(String orderId, String wxOrderId, int status, String openId) {
        //查询祝福表
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Orders::getOrderId, orderId);
        Orders orders = ordersMapper.selectOne(queryWrapper);
        if (orders == null) {
            LOG.error("支付回调查询订单为空 orders={},wxOrderId={},openId={}", orderId, wxOrderId, openId);
        }
        orders.setStatus(status);
        orders.setTransactionId(wxOrderId);
        orders.setUpdateDate(LocalDateTime.now());
        //修改订单状态
        ordersMapper.updateById(orders);
        //加锁变更祈福值
        SetParams sp = new SetParams();
        sp.nx().ex(500);
        var key = "order_blessing_" + orders.getBlessingId();
        var flag = jedisUtil.set(key, "lock", sp);
        if (!flag) {
            return;
        }
        try {
            //查询对应祈福
            Blessing blessing = blessingServiceImpl.getById(orders.getBlessingId());
            blessing.setFuValue(orders.getOrderValue() + blessing.getFuValue());
            blessing.setStatus(Constant.StaticBlessing.STATUS_BLESSING_UNBAN);
            blessing.setUpdateDate(LocalDateTime.now());
            //更新祈福值
            blessing.updateById();
            //zadd加值
            var zaddKey = RedisKey.RANKING_LIST_USER;
            jedisUtil.zincrby(zaddKey, orders.getOrderValue(), blessing.getUserId() + "");
            //删除100名以外的
            Long sum = jedisUtil.zcard(zaddKey);
            if (sum > Constant.RANKING_LIST_NUM) {
                //只保存100人
                jedisUtil.zremrangeByRank(key, 0, sum - Constant.RANKING_LIST_NUM);
            }
        } finally {
            //放锁
            jedisUtil.del(key);
        }
    }

    @Override
    public Orders selectBy() {
        return null;
    }
}
